<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import moment from "moment"
// import { cardDataLoad, boardLoad } from '@/api/share'
var defaultData = () => {
    return [
        ['2023/1/25', 2300, 2291.3, 2288.26, 2308.38],
        ['2023/1/28', 2295.35, 2346.5, 2295.35, 2346.92],
        ['2023/1/29', 2347.22, 2358.98, 2337.35, 2363.8],
        ['2023/1/30', 2360.75, 2382.48, 2347.89, 2383.76],
        ['2023/1/31', 2383.43, 2385.42, 2371.23, 2391.82],
        ['2023/2/1', 2377.41, 2419.02, 2369.57, 2421.15],
        ['2023/2/4', 2425.92, 2428.15, 2417.58, 2440.38],
        ['2023/2/5', 2411, 2433.13, 2403.3, 2437.42],
        ['2023/2/6', 2432.68, 2434.48, 2427.7, 2441.73],
        ['2023/2/7', 2430.69, 2418.53, 2394.22, 2433.89],
        ['2023/2/8', 2416.62, 2432.4, 2414.4, 2443.03],
        ['2023/2/18', 2441.91, 2421.56, 2415.43, 2444.8],
        ['2023/2/19', 2420.26, 2382.91, 2373.53, 2427.07],
        ['2023/2/20', 2383.49, 2397.18, 2370.61, 2397.94],
        ['2023/2/21', 2378.82, 2325.95, 2309.17, 2378.82],
        ['2023/2/22', 2322.94, 2314.16, 2308.76, 2330.88],
        ['2023/2/25', 2320.62, 2325.82, 2315.01, 2338.78],
        ['2023/2/26', 2313.74, 2293.34, 2289.89, 2340.71],
        ['2023/2/27', 2297.77, 2313.22, 2292.03, 2324.63],
        ['2023/2/28', 2322.32, 2365.59, 2308.92, 2366.16],
        ['2023/3/1', 2364.54, 2359.51, 2330.86, 2369.65],
        ['2023/3/4', 2332.08, 2273.4, 2259.25, 2333.54],
        ['2023/3/5', 2274.81, 2326.31, 2270.1, 2328.14],
        ['2023/3/6', 2333.61, 2347.18, 2321.6, 2351.44],
        ['2023/3/7', 2340.44, 2324.29, 2304.27, 2352.02],
        ['2023/3/8', 2326.42, 2318.61, 2314.59, 2333.67],
        ['2023/3/11', 2314.68, 2310.59, 2296.58, 2320.96],
        ['2023/3/12', 2309.16, 2286.6, 2264.83, 2333.29],
        ['2023/3/13', 2282.17, 2263.97, 2253.25, 2286.33],
        ['2023/3/14', 2255.77, 2270.28, 2253.31, 2276.22],
        ['2023/3/15', 2269.31, 2278.4, 2250, 2312.08],
        ['2023/3/18', 2267.29, 2240.02, 2239.21, 2276.05],
        ['2023/3/19', 2244.26, 2257.43, 2232.02, 2261.31],
        ['2023/3/20', 2257.74, 2317.37, 2257.42, 2317.86],
        ['2023/3/21', 2318.21, 2324.24, 2311.6, 2330.81],
        ['2023/3/22', 2321.4, 2328.28, 2314.97, 2332],
        ['2023/3/25', 2334.74, 2326.72, 2319.91, 2344.89],
        ['2023/3/26', 2318.58, 2297.67, 2281.12, 2319.99],
        ['2023/3/27', 2299.38, 2301.26, 2289, 2323.48],
        ['2023/3/28', 2273.55, 2236.3, 2232.91, 2273.55],
        ['2023/3/29', 2238.49, 2236.62, 2228.81, 2246.87],
    ]
}

export default {
    Name: "Candlestick",
    components: {
        echarts
    },
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            showContent: false,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            filterForm: {
                pageInfo: {
                    pageSize: 1,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
            timer: null,
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        reloadInfo() {
            var self = this;

            // 重绘
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            // #region
            const end = new Date();
            const start = new Date();
            if (this.obj.tableData.type == 0) {
                this.filterForm.isOnlie = true;

                // 查询一天内数据
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                this.filterForm.beginTime = this.parseTime(start);
                this.filterForm.endTime = this.parseTime(end);
            } else {
                this.filterForm.isOnlie = false;

                start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d}");
                this.filterForm.endTime = this.parseTime(end);

                // 刷新时间兼容处理
                if (timeSize < 60) {
                    timeSize = 60;
                }
            }
            // #endregion

            clearInterval(this.timer);

            this.getLineData((dataResult) => {
                self.setOptions(dataResult.dataList);
            });

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end);

                    this.getLineData((dataResult) => {
                        self.setOptions(dataResult.dataList);
                    });
                }, timeSize * 1000);
            }
        },
        // 数据转换
        // resultDataToObject(dataResult) {
        //     var xData = [];
        //     var serveData = [];
        //     var columns = [];
        //     if (dataResult.dataList && dataResult.columns) {
        //         var dataList = dataResult.dataList.reverse();
        //         dataResult.columns.forEach((x, j) => {
        //             if (j > 0) {
        //                 columns.push(x.name)
        //             }
        //         })

        //         for (var i = 0; i < dataResult.dataList[0].length; i++) {
        //             var data = [];
        //             dataList.forEach((x, j) => {
        //                 data.push(x[i]);
        //             });
        //             if (i == 0) {
        //                 xData = data;
        //             } else {
        //                 serveData.push(data);
        //             }
        //         }
        //     }
        //     return {
        //         expectedData: xData,
        //         columns,
        //         actualData: serveData
        //     }
        // },
        setStyle() {
            var style = this.obj.style;

            // #region 组件背景图或颜色
            var backgroundColor = "";
            var backgroundImage = "";

            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "";
            }
            // #endregion

            // #region 组件投影
            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }
            // #endregion

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                // backgroundImage,
                // backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions(dataArray) {
            var self = this;

            var data = this.splitData(dataArray);
            // console.log(data);

            // #region 系列颜色
            // var colors = ['#fc8251', '#5470c6', '#91cd77', '#ef6567', '#f9c956', '#75bedc'];
            // var newColors = [];
            // this.obj.tableData.barList.forEach((e, index) => {
            //     if (e.color) {
            //         newColors.push(e.color);
            //     }
            // });
            // if (this.obj.tableData.colors) {
            //     newColors = this.obj.tableData.colors;
            // } else {
            //     newColors = newColors.concat(colors);
            // }
            var color = "#333333";
            if (this.obj.tableData.color) {
                color = this.obj.tableData.color;
            }
            var lineColor = "#eeeeee"
            if (this.obj.tableData.lineColor) {
                lineColor = this.obj.tableData.lineColor;
            }
            // #endregion

            // #region 图例 legend样式
            // var isShowLegend = true;
            // if (this.obj.tableData.isShowLegend != undefined) {
            //     isShowLegend = this.obj.tableData.isShowLegend;
            // }
            // var icon = "circle";
            // if (this.obj.tableData.icon) {
            //     icon = this.obj.tableData.icon;
            // }

            // var textColor = "#333333";
            // if (this.obj.tableData.textColor) {
            //     textColor = this.obj.tableData.textColor;
            // }
            // var textFontsize = '14px';
            // if (this.obj.tableData.textfontSize) {
            //     textFontsize = this.obj.tableData.textfontSize + "px";
            // }
            // var textFontWeight = "";
            // if (this.obj.tableData.textFontWeight) {
            //     textFontWeight = this.obj.tableData.textFontWeight;
            // }
            // var textFontStyle = "";
            // if (this.obj.tableData.textFontStyle) {
            //     textFontStyle = this.obj.tableData.textFontStyle;
            // }

            // var orient = 'horizontal';
            // if (this.obj.tableData.orient) {
            //     orient = this.obj.tableData.orient;
            // }
            // var top = "";
            // var left = "";
            // var right = "";
            // if (this.obj.tableData.leftPosition == 1) {
            //     if (this.obj.tableData.topPosition == 1) {
            //         top = "center"
            //     } else if (this.obj.tableData.topPosition == 2) {
            //         top = "bottom"
            //     } else {
            //         top = "0"
            //     }
            //     left = 'center';
            // } else if (this.obj.tableData.leftPosition == 2) {
            //     if (this.obj.tableData.topPosition == 1) {
            //         top = "center"
            //     } else if (this.obj.tableData.topPosition == 2) {
            //         top = "bottom"
            //     } else {
            //         top = "0"
            //     }
            //     left = undefined;
            //     right = 0;
            // } else {
            //     if (this.obj.tableData.topPosition == 1) {
            //         top = "center"
            //     } else if (this.obj.tableData.topPosition == 2) {
            //         top = "bottom"
            //     } else {
            //         top = "0"
            //     }
            //     left = 'left';
            // }

            // #endregion

            // #region 标签样式
            // var decimal = 0;
            // if (this.obj.tableData.decimal) {
            //     decimal = this.obj.tableData.decimal;
            // }

            // var isShowLabel = false;
            // if (this.obj.tableData.isShowValue) {
            //     isShowLabel = this.obj.tableData.isShowValue;
            // }
            // var valColor = "#333333";
            // if (this.obj.tableData.valueColor) {
            //     valColor = this.obj.tableData.valueColor;
            // }
            // var valFontsize = '14px';
            // if (this.obj.tableData.valuefontSize) {
            //     valFontsize = this.obj.tableData.valuefontSize + "px";
            // }
            // var valFontWeight = "";
            // if (this.obj.tableData.valueFontWeight) {
            //     valFontWeight = this.obj.tableData.valueFontWeight;
            // }
            // var valFontStyle = "";
            // if (this.obj.tableData.valueFontStyle) {
            //     valFontWeight = this.obj.tableData.valueFontStyle;
            // }
            // // 标签位置
            // var lablePosition = undefined;
            // if (this.obj.tableData.lablePosition) {
            //     lablePosition = this.obj.tableData.lablePosition;

            //     if (this.obj.tableData.isZong) {
            //         if (this.obj.tableData.lablePosition == "insideTop") {
            //             lablePosition = "insideRight";
            //         } else if (this.obj.tableData.lablePosition == "top") {
            //             lablePosition = "right";
            //         }
            //     }
            // }
            // #endregion

            //  #region 数据 图形
            // var seriesData = [];
            // columns.forEach((x, i) => {
            //     var item = {
            //         type: 'bar',
            //         stack: this.obj.tableData.iSstack,
            //         name: x,
            //         data: actualData[i],
            //         // barWidth: "30",
            //         showBackground: this.obj.tableData.showBackground,
            //         backgroundStyle: {
            //             color: this.obj.tableData.backgroundStyleColor
            //         },
            //         label: {
            //             show: isShowLabel,
            //             position: lablePosition,
            //             formatter: function (param) {
            //                 return Number(param.value).toFixed(decimal);
            //             },
            //             color: valColor,
            //             fontSize: valFontsize,
            //             fontWeight: valFontWeight,
            //             fontStyle: valFontStyle,
            //         },
            //     };
            //     seriesData.push(item);
            // })
            // #endregion

            this.chart.setOption({
                grid: {
                    left: "2%",
                    right: "6%",
                    top: "60px",
                    bottom: "10px",
                    containLabel: true
                },
                // color: newColors,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                // legend: {
                //     top: "25px",
                //     left: "15px",
                //     show: isShowLegend,
                //     // orient: orient,
                //     right: 10,
                //     textStyle: {
                //         color: textColor,
                //         fontSize: textFontsize,
                //         fontWeight: textFontWeight,
                //         fontStyle: textFontStyle,
                //     },
                //     icon,
                //     formatter: (val) => {
                //         return val;
                //     }
                // },
                xAxis: {
                    type: 'category',
                    data: data.categoryData.map(function (str) {
                        if (!isNaN(Date.parse(str)) && Date.parse(str) > 631152000000) {
                            return moment(str).format("YYYY/MM/DD") + "\n" + moment(str).format("HH:mm:ss")
                        }
                        return str;
                    }),
                    scale: true,
                    // boundaryGap: false,
                    axisLine: { onZero: false },
                    splitLine: { show: false },
                    axisLabel: {
                        color: color,
                    },
                    // splitNumber: 20,
                    min: 'dataMin',
                    max: 'dataMax'
                },
                yAxis: {
                    scale: true,
                    axisLabel: {
                        color: color,
                    },
                    splitLine: {
                        show: this.obj.tableData.isShowGrid,
                        lineStyle: {
                            color: lineColor,
                            width: 1,
                        }
                    },
                },
                series: [
                    {
                        type: 'candlestick',
                        data: data.values,
                        markLine: {
                            symbol: ['none', 'none'],
                            data: [
                                {
                                    name: 'min line on close',
                                    type: 'min',
                                    valueDim: 'close'
                                },
                                {
                                    name: 'max line on close',
                                    type: 'max',
                                    valueDim: 'close'
                                }
                            ]
                        }
                    }
                ]
            });
        },
        splitData(rawData) {
            console.log(rawData);
            var categoryData = [];
            var values = [];
            // var itemStyle1 = {
            //     color: "rgba(84,252,252, 0)", //"rgba(84,252,252, 1)",
            //     color0: "rgba(84,252,252, 1)",
            //     borderColor: "rgba(84,252,252, 1)",
            //     borderColor0: "rgba(84,252,252, 1)",
            // };
            for (var i = 0; i < rawData.length; i++) {
                var info = rawData[i];
                categoryData.push(info.splice(0, 1)[0]);
                values.push(info)
            }
            return {
                categoryData: categoryData,
                values: values
            };
        },
        getLineData(callback) {
            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId || !this.obj.tableData.xId) {
                this.showContent = true;

                this.setOptions(defaultData());
                return false;
            }
            // #endregion

            // #region 参数不完整
            var idlist = [this.obj.tableData.xId];
            if (this.obj.tableData.barList.length == 0) {
                this.showContent = false;
                return false;
            }
            this.obj.tableData.barList.forEach(e => {
                if (e.id) {
                    idlist.push(e.id);
                }
            });
            if (idlist.length - 1 != this.obj.tableData.barList.length) {
                this.showContent = false;
                return false;
            }
            // #endregion

            this.showContent = true;
            this.filterForm.tableId = this.obj.tableData.tableId;
            this.filterForm.pageInfo.pageSize = this.obj.tableData.count;
            this.filterForm.structureIds = idlist;

            if (this.obj.tableData.type != 1) {
                cardDataLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            } else {
                boardLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            }
        }
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>